<%@page contentType="text/html; charset=UTF-8"%>
<%@ page import="java.awt.*"%>
<%@ page import="java.io.*"%>
<%@ page import="java.util.*"%>
<%@ page import="com.gzgi.framework.*"%>
<%@ page import="com.gzgi.framework.el.*"%>
<%@ page import="com.gzgi.framework.util.*"%>
<%@ page import="com.gzgi.framework.config.*"%>
<%@ page import="com.gzgi.framework.context.*"%>
<%@ page import="com.gzgi.framework.chart.*"%>
<%@ page import="com.gzgi.framework.entity.*"%>
<%@ page import="com.gzgi.framework.dataitem.*"%>
<%@ page import="com.gzgi.framework.sys.model.*"%>
<%@ page import="com.gzgi.framework.sys.util.*"%>
<%@ page import="com.gzgi.crm.context.*"%>
<%@ page import="com.gzgi.crm.report.*"%>
<%@ page import="com.gzgi.crm.service.*"%>
<%@ page import="com.gzgi.crm.model.*"%>
<%@ page import="org.apache.commons.lang.StringUtils"%>
<%@ page import="org.jfree.chart.*"%>
<%@ page import="org.jfree.chart.axis.*"%>
<%@ page import="org.jfree.chart.plot.*"%>
<%@ page import="org.jfree.chart.renderer.category.*"%>
<%@ page import="org.jfree.chart.title.*"%>
<%@ page import="org.jfree.data.category.*"%>
<%@ page import="org.jfree.ui.*"%>
<%@ page import="org.jfree.chart.servlet.ServletUtilities"%>
<%@ page import="org.jfree.chart.labels.*"%>
<%@ page import="org.jfree.chart.imagemap.*"%>
<%@ page import="org.jfree.chart.urls.StandardPieURLGenerator"%>
<%@ page import="org.jfree.chart.entity.StandardEntityCollection"%>
<%@ page import="org.jfree.data.general.DefaultPieDataset"%>
<%!
    class CustomBarRenderer extends BarRenderer
    {

        public Paint getItemPaint(int i, int j)
        {
            return colors[j % colors.length];
        }

        private Paint colors[];

        public CustomBarRenderer(Paint apaint[])
        {
            colors = apaint;
        }
    }

   private static Paint[] createPaint()
    {
        Paint apaint[] = new Paint[3];
        apaint[0] = new GradientPaint(0.0F, 0.0F, Color.white, 0.0F, 0.0F, Color.green);
        apaint[1] = new GradientPaint(0.0F, 0.0F, Color.white, 0.0F, 0.0F, Color.yellow);
		apaint[2] = new GradientPaint(0.0F, 0.0F, Color.white, 0.0F, 0.0F, Color.red);
        return apaint;
    }

%>
<%
		      SecurityContext securityContext = RequestUtil.getSecurityContext(request);;
			  Collection roleIds = securityContext.getRoles();
			  User user = RequestUtil.getUser(request);

			  String actorId = user.getActorId();
			  String complexQuery = request.getParameter("complexQuery");
			 
			  Map queryParams = RequestUtil.getQueryParams(request);
			  Map paramMap = RequestUtil.getParameterMap(request);

              String groupBy = request.getParameter("groupBy");
			  String teamType = (String) queryParams.get("teamType");
		      String observerId = (String) queryParams.get("observerId");
			  String x_q_flag = request.getParameter("x_q_flag");

			  if(StringUtils.isEmpty(teamType)){
				  teamType = request.getParameter("teamType");
			  }

			 if(StringUtils.isEmpty(teamType)){
				  teamType = "xyz";
			  }

			  if(StringUtils.isEmpty(observerId)){
				  observerId = request.getParameter("observerId");
			  }

			  if(StringUtils.isEmpty(observerId)){
				  observerId = (String)request.getSession().getAttribute("x_observerId");
			  }

			  Collection actorIds = new HashSet();

			   if (roleIds == null) {
					roleIds = new HashSet();
					roleIds.add("everyone");
			   }

 							
			   SalesContext ctx = new SalesContext();
			   ctx.setQueryParams(queryParams);
			   ctx.setActorId(actorId);
			   ctx.setObserverId(observerId);
			   ctx.setTeamType(teamType);
			   SalesHelper helper = new SalesHelper();
			   Collection userIds = helper.getActorIds(ctx);
 
				if(userIds != null ){
					 actorIds.addAll(userIds);
				} 
				
			 if(actorIds.size() == 0){
				   if (!(roleIds.contains(SecurityContext.SENIOR_MANAGER)
					    || roleIds.contains(SecurityContext.GENERAL_MANAGER)
						|| roleIds.contains(SecurityContext.SYSTEM_REVIEWER))){
						 actorIds.add(actorId);
					 }
			   }

			 Map params = new HashMap();

			 if(StringUtils.isNotEmpty(complexQuery)){
               Map xMap = JSONTools.decode(complexQuery);
			   if(xMap != null && xMap.size() > 0){
                  params.putAll(xMap);
			   }
		    }

			 params.putAll(queryParams);

			 if(actorIds.size() > 0){
				 params.put("x_actorIds", actorIds.toArray());
			 }

		  params.put("teamType", teamType);

		  params.put("observerId", observerId);

		  String queryString = JSONTools.encode(params);

		  
		  queryString = RequestUtil.encodeString(queryString);

		  ctx.setQueryParams(params);
		  ctx.setActorId(user.getActorId());
		  ctx.setObserverId(observerId);
		  ctx.setTeamType(teamType);

		  java.util.List itemsX = new ArrayList();

          java.util.List rows = null;
		  ReportService reportService = null;
		  DataItemService dataItemService = null;
		  try {
			  dataItemService = (DataItemService) ContextFactory.getBean("dataItemService");
			  reportService = (ReportService)ContextFactory.getBean("reportService");
			  rows = reportService.getSaleLogTypes(ctx);
               
		    java.util.List dataItemsX = dataItemService.getDataItems("saleLogTypeCode");
			if(dataItemsX != null && dataItemsX.size() > 0){
			   Iterator it007 = dataItemsX.iterator();
			   while(it007.hasNext()){
				  itemsX.add(it007.next());
			   }
			}

		  } catch(Exception ex){
                ex.printStackTrace();
	      }

		if(rows == null || rows.size() == 0){
			 out.println("<br><br><div align=\"center\">没有满足条件的数据。</div><br><br>");
			 return;
		}

        Map rowMap = new HashMap();
         
		double total = 0.0;

        if(rows != null && rows.size() > 0){
              Iterator iterator4 = rows.iterator();
	          while(iterator4.hasNext()){
				  SaleLog saleLog = (SaleLog)iterator4.next();
				  String x = saleLog.getLogTypeCode();
				  double xyz = saleLog.getHours();
				  if(x != null && xyz >0){
					  total = total + xyz;
					  String complexKey = x ;
					  Double d = (Double)rowMap.get(complexKey);
					  if(d == null){
						  d = new Double(0.0);
					  }
					  d = new Double(d.doubleValue() + xyz);
					  rowMap.put(complexKey, d);
				  }
			  }
		}

		 if(itemsX.size() > 0  ){
			DefaultCategoryDataset dataset = new DefaultCategoryDataset();
			Iterator iterator = itemsX.iterator();
			while(iterator.hasNext()){
				DataItem item1 = (DataItem)iterator.next();
				String x =  item1.getCode();
				String title = item1.getName();				 
				String complexKey = x ;
				Double d = (Double)rowMap.get(complexKey);
				if(d != null){
						dataset.addValue(d.doubleValue() , item1.getName(), title);
			     } else {
						dataset.addValue(0.000000D , item1.getName(), title);
				 }
			 }
	

        String seriesTitle = "项目阶段用时（小时）";
		String label = "（小时）";
        String labelx = "总用时";
	   

	    JFreeChart jfreechart = ChartFactory.createStackedBarChart("项目用时状态分布图  " +labelx + Math.round(total)+label,
			                                     "日志类型", seriesTitle, dataset, PlotOrientation.VERTICAL, true, true, false);

        jfreechart.setBackgroundPaint(Color.white);   
	    CategoryPlot categoryplot = jfreechart.getCategoryPlot();
        jfreechart.setBackgroundPaint(Color.white);   

		ExtendedStackedBarRenderer render = new ExtendedStackedBarRenderer();
		render.setItemLabelsVisible(true);
		render.setItemLabelGenerator(new org.jfree.chart.labels.StandardCategoryItemLabelGenerator());
		render.setToolTipGenerator(new org.jfree.chart.labels.StandardCategoryToolTipGenerator());

        Paint red = new GradientPaint(0.0F, 0.0F, Color.white, 0.0F, 0.0F, Color.red);
        Paint green = new GradientPaint(0.0F, 0.0F, Color.white, 0.0F, 0.0F, Color.green);
        Paint blue= new GradientPaint(0.0F, 0.0F, Color.white, 0.0F, 0.0F, Color.blue);
        Paint orange= new GradientPaint(0.0F, 0.0F, Color.white, 0.0F, 0.0F, Color.orange);
        Paint magenta= new GradientPaint(0.0F, 0.0F, Color.white, 0.0F, 0.0F, Color.magenta);

		render.setSeriesPaint(0, Color.green);
		render.setSeriesPaint(1, Color.yellow);
		render.setSeriesPaint(2, Color.red);
		render.setItemMargin(2);

		render.setItemURLGenerator(new ChartCategoryURLGenerator(request.getContextPath()+"/pages/crm/salelog/forward.jsp?complexQuery="+queryString,
				"query_x_salelog_logTypeCode", "query_x_salelog_logType"));
		render.setToolTipGenerator(new org.jfree.chart.labels.StandardCategoryToolTipGenerator());

		categoryplot.setRenderer(render);

		ValueAxis valueaxis = categoryplot.getRangeAxis();
		valueaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
		valueaxis.setLowerMargin(0.14999999999999999D);
		valueaxis.setUpperMargin(0.14999999999999999D);

		if(StringUtils.equals(x_q_flag, "1")){
%>
<jsp:include page="/pages/tm/header.jsp" />
<%
		}
		
		int width = 920;
	    int height = 420;
		String dataFile = "x_salelog_logtype";
        String path = ApplicationContext.getAppPath()+"/temp/";
		try {
			 ChartRenderingInfo info = new ChartRenderingInfo(
					new org.jfree.chart.entity.StandardEntityCollection());

			 java.awt.image.BufferedImage bi = jfreechart.createBufferedImage(
					width, height, info);
			
			 OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(new File(path + dataFile
									+ teamType +"_"+queryString.hashCode()  + ".png")));
			 com.keypoint.PngEncoder encoder = new com.keypoint.PngEncoder(bi, false, 0, 1);
			 byte[] bytes = encoder.pngEncode();
			 outputStream.write(bytes);
			 outputStream.close();

			String content = "<script language=\"JavaScript\">"
							+ "function overlib(){"
							+ "}"
							+ "function nd(){"
							+ "}" + "</script>\n";

			content += org.jfree.chart.imagemap.ImageMapUtilities.getImageMap( "map_logtype_"+queryString.hashCode() +teamType, info, new ChartToolTipTagFragmentGenerator(), new ChartURLTagFragmentGenerator());
			content +="<p align=\"center\">\n<br/>\n<br/>\n<img src=\""+request.getContextPath()+"/temp/"
					+ dataFile + teamType +"_"+queryString.hashCode() + ".png\" usemap=\"#map_logtype_"+queryString.hashCode() +teamType+"\" border=\"0\">\n</p>";
		
			out.println(content);
		} catch (IOException ex) {
			ex.printStackTrace();
		} 
   }
   if(StringUtils.equals(x_q_flag, "1")){
%>
<jsp:include page="/pages/tm/footer.jsp" />
<%
		}
%>